package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.CostListAdater;
import com.sk.cardeal.adapter.FixPartsAdapter;
import com.sk.cardeal.adapter.FixProjectAdapter;
import com.sk.cardeal.adapter.FormProjectAdapter;
import com.sk.cardeal.adapter.NewFixByAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.callback.PriceChangedCallback;
import com.sk.cardeal.common.Constants;
import com.sk.cardeal.entity.ApplyFormEntity;
import com.sk.cardeal.entity.ByKindList;
import com.sk.cardeal.entity.ByPartsEntity;
import com.sk.cardeal.entity.CostType;
import com.sk.cardeal.entity.NewPartsList;
import com.sk.cardeal.entity.PartsListBean;
import com.sk.cardeal.entity.Project;
import com.sk.cardeal.entity.ProjectListBean;
import com.sk.cardeal.entity.RepairOrderDetail;
import com.sk.cardeal.entity.WorkFormDetails;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.view.IconViewTextView;
import com.sk.cardeal.view.LineMenuView;
import com.sk.cardeal.view.TitleView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.sk.cardeal.common.Constants.CHOOSE_PARTS;
import static com.sk.cardeal.common.Constants.CHOOSE_PROJECT;
import static com.sk.cardeal.common.Constants.OTHER_PAY;

/**
 * Created by sk on 2018/2/1.
 */

public class EditWorkFormActivity extends BaseActivity implements HandleDataCallBack, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, PriceChangedCallback {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.scan)
    ImageView scan;
    @BindView(R.id.car_num)
    TextView carNum;
    @BindView(R.id.car_type)
    LineMenuView carType;
    @BindView(R.id.fix_type)
    LineMenuView fixType;
    @BindView(R.id.scan_frame)
    ImageView scanFrame;
    @BindView(R.id.frame_num)
    TextView frameNum;
    @BindView(R.id.fix_pep)
    LineMenuView fixPep;
    @BindView(R.id.in_date)
    LineMenuView inDate;
    @BindView(R.id.danwei)
    TextView danwei;
    @BindView(R.id.ed_in_km)
    TextView edInKm;
    @BindView(R.id.car_owner)
    TextView carOwner;
    @BindView(R.id.send_pep)
    TextView sendPep;
    @BindView(R.id.phone)
    TextView phone;
    @BindView(R.id.finish_date)
    LineMenuView finishDate;
    @BindView(R.id.ed_card_num)
    TextView edCardNum;
    @BindView(R.id.ed_advice)
    TextView edAdvice;
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.close_ll)
    FrameLayout closeLl;
    @BindView(R.id.detail_ll)
    LinearLayout detailLl;
    @BindView(R.id.card_head)
    ImageView cardHead;
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.s_fix_type)
    LineMenuView sFixType;
    @BindView(R.id.open)
    ImageView open;
    @BindView(R.id.open_ll)
    FrameLayout openLl;
    @BindView(R.id.simple_ll)
    LinearLayout simpleLl;
    @BindView(R.id.project)
    IconViewTextView project;
    @BindView(R.id.project_ryc)
    RecyclerView projectRyc;
    @BindView(R.id.parts)
    IconViewTextView parts;
    @BindView(R.id.parts_ryc)
    RecyclerView partsRyc;
    @BindView(R.id.other_pay)
    IconViewTextView otherPay;
    @BindView(R.id.other_ryc)
    RecyclerView otherRyc;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.parts_by)
    IconViewTextView partsBy;
    @BindView(R.id.parts_by_ryc)
    RecyclerView partsByRyc;

    private String orderId = "";
    private ApplyFormEntity applyFormEntity;

    private LoadingDialog loadingDialog;

    private ArrayList<ByKindList.ResultListBean> allByPartsList = new ArrayList<>();

    private ArrayList<NewPartsList.ResultListBean.PartsQualityListBean> selectList = new ArrayList<>();

    private ArrayList<Project> selectProjectList = new ArrayList<>();

    private ArrayList<ByKindList.ResultListBean> selectByPartsList = new ArrayList<>();

    private List<CostType> costTypeList = new ArrayList<>();

    private FixPartsAdapter fixPartsAdapter;

    private NewFixByAdapter fixByPartsAdapter;

    private FixProjectAdapter fixProjectAdapter;

    private CostListAdater costListAdater;

    private FormProjectAdapter formProjectAdapter;

    private String carCode;

    private int formType;

    private List<RepairOrderDetail> repairOrderDetails = new ArrayList<>();
    private String typeId;

    @Override
    protected int getContentView() {
        return R.layout.activity_edit_work_form;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);


        orderId = getIntent().getStringExtra("orderId");
        formType = getIntent().getIntExtra("formType", 0);

        intRyc();


        applyFormEntity = new ApplyFormEntity();
        applyFormEntity.setId(orderId);
        loadingDialog.show();
        AppApi.workFormDetails(orderId, this, 200, this);

    }


    private void intRyc() {
        partsRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixPartsAdapter = new FixPartsAdapter(R.layout.item_fix_parts, selectList,this);
        partsRyc.setAdapter(fixPartsAdapter);
        fixPartsAdapter.setOnItemClickListener(this);
        fixPartsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.finish_edit:
                        TextView textView = (TextView) adapter.getViewByPosition(partsRyc, position, R.id.edit_num);
                        int count = Integer.parseInt(textView.getText().toString());
                        if (count != 0) {
                            selectList.get(position).setWantCount(count);
                            selectList.get(position).setOpen(false);
                            adapter.notifyItemChanged(position);
                        } else {
                            selectList.remove(position);
                            adapter.notifyDataSetChanged();
                        }

                        break;
                    case R.id.edit_btn:
                        selectList.get(position).setOpen(true);
                        adapter.notifyItemChanged(position);
                        break;
                }
            }
        });


        partsByRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixByPartsAdapter = new NewFixByAdapter(R.layout.item_new_fix_by_parts, selectByPartsList);
        partsByRyc.setAdapter(fixByPartsAdapter);
        fixByPartsAdapter.setOnItemClickListener(this);
        fixByPartsAdapter.setOnItemChildClickListener(this);

        projectRyc.setLayoutManager(new LinearLayoutManager(mContext));
        if (formType == 1) {
            fixProjectAdapter = new FixProjectAdapter(R.layout.item_quickly_fix_project, selectProjectList);
            projectRyc.setAdapter(fixProjectAdapter);
            fixProjectAdapter.setOnItemClickListener(this);
            fixProjectAdapter.setOnItemChildClickListener(this);

        } else {
            formProjectAdapter = new FormProjectAdapter(R.layout.item_fix_project, selectProjectList);
            projectRyc.setAdapter(formProjectAdapter);
            formProjectAdapter.setOnItemClickListener(this);
            formProjectAdapter.setOnItemChildClickListener(this);
        }


        otherRyc.setLayoutManager(new LinearLayoutManager(mContext));
        costListAdater = new CostListAdater(R.layout.item_cost, costTypeList);
        otherRyc.setAdapter(costListAdater);
        costListAdater.setOnItemClickListener(this);
        costListAdater.setOnItemChildClickListener(this);


        partsRyc.setHasFixedSize(true);
        partsRyc.setNestedScrollingEnabled(false);

        projectRyc.setHasFixedSize(true);
        projectRyc.setNestedScrollingEnabled(false);

        otherRyc.setHasFixedSize(true);
        otherRyc.setNestedScrollingEnabled(false);
    }


    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
        }
    }


    @OnClick({R.id.parts_by, R.id.project, R.id.parts, R.id.other_pay, R.id.save, R.id.finish_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.parts_by:
                loadingDialog.show();
                AppApi.getByPartsByKm(carCode, edInKm.getText().toString(), EditWorkFormActivity.this, 400, EditWorkFormActivity.this);
                break;

            case R.id.project:

                loadingDialog.show();
                AppApi.getFixProject(formType, EditWorkFormActivity.this, 6, EditWorkFormActivity.this);

                break;
            case R.id.parts:

                if (typeId != null && typeId.length() > 0) {
                    Intent intent = new Intent(mContext, NewChoosePartsActivity.class);
                    intent.putExtra("id", typeId);
                    intent.putExtra("data", selectList);
                    startActivityForResult(intent, Constants.CHOOSE_PARTS);
                } else {
                    Toast.makeText(mContext, "请先选择车型！", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.other_pay:
                Intent costIntent = new Intent(mContext, NewCostActivity.class);
                startActivityForResult(costIntent, OTHER_PAY);
                break;
            case R.id.save:
                loadingDialog.show();
                setData();
                AppApi.updateProjectInfo(applyFormEntity, EditWorkFormActivity.this, 0, EditWorkFormActivity.this);
                break;
            case R.id.finish_date:

                DatePickDialog dialog1 = new DatePickDialog(this);
                //设置上下年分限制
                dialog1.setYearLimt(5);
                //设置标题
                dialog1.setTitle("选择预计完工日期");
                //设置类型
                dialog1.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog1.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog1.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog1.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        finishDate.setHint(MyUtils.stampToDate(date.getTime()));
                        applyFormEntity.setAboutOverTime(MyUtils.stampToDate(date.getTime()));
                        finishDate.setHintColor(Color.parseColor("#232323"));
                    }
                });
                dialog1.show();

                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 200:

                //保存订单后进入
                WorkFormDetails workFormDetails = JSON.parseObject(result, WorkFormDetails.class);

                carCode = workFormDetails.getReturnObject().getCarCode();

                //车型
                carType.setHint(workFormDetails.getReturnObject().getCarName());
                carType.setHintColor(Color.parseColor("#232323"));
                typeId = workFormDetails.getReturnObject().getCarTypeId();


                frameNum.setText(workFormDetails.getReturnObject().getCarVin());
                carNum.setText(workFormDetails.getReturnObject().getCarNumber());
                sendPep.setText(workFormDetails.getReturnObject().getSendRepairUserName());
                carOwner.setText(workFormDetails.getReturnObject().getCustomName());

                fixType.setHint(workFormDetails.getReturnObject().getRepairName());
                fixType.setHintColor(Color.parseColor("#232323"));

                //主修人
                fixPep.setHint(workFormDetails.getReturnObject().getMainName());
                fixPep.setHintColor(Color.parseColor("#232323"));

                //进场日期
                inDate.setHint(workFormDetails.getReturnObject().getInTime());
                inDate.setHintColor(Color.parseColor("#232323"));

                //预计完成日期
                finishDate.setHint(workFormDetails.getReturnObject().getInTime());
                finishDate.setHintColor(Color.parseColor("#232323"));

                edInKm.setText(workFormDetails.getReturnObject().getMileage());
                edAdvice.setText(workFormDetails.getReturnObject().getRepairTips());
                phone.setText(workFormDetails.getReturnObject().getPhone());
                edCardNum.setText(workFormDetails.getReturnObject().getVipNumber());

                List<WorkFormDetails.ReturnObjectBean.RepairOrderDetailListBean> dataBeanList = workFormDetails.getReturnObject().getRepairOrderDetailList();
                for (WorkFormDetails.ReturnObjectBean.RepairOrderDetailListBean detailListBean : dataBeanList) {
                    switch (detailListBean.getType()) {
                        case 1:
                            Project project = new Project();
                            project.setSelect(true);
                            project.setId(detailListBean.getRepairProId());
                            project.setProjectName(detailListBean.getProject_name());
                            project.setEditPrice(detailListBean.getOtherPrice());
                            selectProjectList.add(project);
                            break;
                        case 2:
                            NewPartsList.ResultListBean.PartsQualityListBean parts = new NewPartsList.ResultListBean.PartsQualityListBean();
                            parts.setWantCount(detailListBean.getNum());
                            parts.setEditPrice(detailListBean.getOtherPrice());
                            parts.setCarWarehousePartsId(detailListBean.getPartId());
                            parts.setPartsName(detailListBean.getPartName());
                            parts.setPartsOeCode(detailListBean.getGoodsCode());
                            selectList.add(parts);
                            break;
                        case 3:
                            CostType costType = new CostType();
                            costType.setRemark(detailListBean.getOtherRemark());
                            costType.setCostName(detailListBean.getOtherName());
                            costType.setCost(String.valueOf(detailListBean.getOtherCost()));
                            costType.setPrice(String.valueOf(detailListBean.getOtherPrice()));
                            costTypeList.add(costType);
                            break;
                    }
                }

                if(workFormDetails.getReturnObject().getBasePartsCategoryList()!=null&&workFormDetails.getReturnObject().getBasePartsCategoryList().size()>0){
                    for(ByKindList.ResultListBean data : workFormDetails.getReturnObject().getBasePartsCategoryList()){
                        if(data.getId() == null){
                            data.setId("0");
                            data.setPartsName(""+data.getCarPartsList().get(0).getMileage()+"公里保养服务");
                            selectByPartsList.add(0,data);
                        }else {
                            selectByPartsList.add(data);
                        }
                    }
                }

                if (formType == 1) {
                    fixProjectAdapter.notifyDataSetChanged();
                } else {
                    formProjectAdapter.notifyDataSetChanged();
                }
                fixByPartsAdapter.notifyDataSetChanged();
                fixPartsAdapter.notifyDataSetChanged();
                costListAdater.notifyDataSetChanged();
                break;
            case 0:
                setResult(RESULT_OK);
                finish();
                break;

            case 3:
                PartsListBean partsListBean = JSON.parseObject(result, PartsListBean.class);
                ArrayList<PartsListBean.ResultListBean> partsList = (ArrayList<PartsListBean.ResultListBean>) partsListBean.getResultList();
                Intent partsIntent = new Intent(mContext, ChoosePartsActivity.class);
                partsIntent.putExtra("data", partsList);
                partsIntent.putExtra("type", typeId);
                partsIntent.putExtra("select", selectList);
                startActivityForResult(partsIntent, CHOOSE_PARTS);
                break;
            case 6:
                ProjectListBean projectListBean = JSON.parseObject(result, ProjectListBean.class);
                ArrayList<Project> projectArrayList = (ArrayList<Project>) projectListBean.getResultList();
                Intent projectIntent = new Intent(mContext, ChooseFixProjectActivity.class);
                projectIntent.putParcelableArrayListExtra("data", projectArrayList);
                projectIntent.putParcelableArrayListExtra("select", selectProjectList);
                startActivityForResult(projectIntent, CHOOSE_PROJECT);
                break;
            case 400:
                Intent byIntent = new Intent(mContext, NewChooseByPartsActivity.class);
                byIntent.putExtra("data", result);
                byIntent.putExtra("carCode", carCode);
                byIntent.putExtra("km", edInKm.getText().toString());
                byIntent.putExtra("selectData",selectByPartsList);
                byIntent.putParcelableArrayListExtra("list", allByPartsList);
                startActivityForResult(byIntent, Constants.CHOOSE_BY_PARTS);
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        if (adapter instanceof FixProjectAdapter) {
            switch (view.getId()) {
                case R.id.right:
                    selectProjectList.remove(position);
                    fixProjectAdapter.notifyDataSetChanged();
                    break;

            }
        } else if (adapter instanceof CostListAdater) {
            switch (view.getId()) {
                case R.id.right:
                    costTypeList.remove(position);
                    costListAdater.notifyDataSetChanged();
                    break;
            }
        } else if (adapter instanceof FormProjectAdapter) {
            switch (view.getId()) {
                case R.id.right:
                    selectProjectList.remove(position);
                    fixProjectAdapter.notifyDataSetChanged();
                    break;

                case R.id.finish_edit:
                    selectProjectList.get(position).setOpen(false);
                    EditText editText = (EditText) adapter.getViewByPosition(projectRyc, position, R.id.price);
                    selectProjectList.get(position).setEditPrice(Double.parseDouble(editText.getText().toString()));
                    fixProjectAdapter.notifyItemChanged(position);
                    break;

                case R.id.edit_btn:
                    selectProjectList.get(position).setOpen(true);
                    adapter.notifyItemChanged(position);
                    break;

            }
        }
    }


    private void setData() {

        for (Project project : selectProjectList) {

            RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
            repairOrderDetail.setType(1);
            repairOrderDetail.setNum(1);
            repairOrderDetail.setRepairProId(project.getId());
            repairOrderDetail.setOtherPrice(project.getAfterCutPrice());
            repairOrderDetails.add(repairOrderDetail);

        }

        for (NewPartsList.ResultListBean.PartsQualityListBean parts : selectList) {

            RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
            repairOrderDetail.setType(2);
            repairOrderDetail.setNum(parts.getWantCount());
            repairOrderDetail.setPartId(parts.getCarWarehousePartsId());
            repairOrderDetail.setOtherPrice(parts.getEditPrice());
            repairOrderDetails.add(repairOrderDetail);

        }

        for (CostType costType : costTypeList) {
            RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
            repairOrderDetail.setType(3);
            repairOrderDetail.setNum(1);
            repairOrderDetail.setOtherName(costType.getCostName());
            repairOrderDetail.setOtherPrice(Double.parseDouble(costType.getPrice()));
            repairOrderDetail.setOtherCost(Double.parseDouble(costType.getCost()));
            repairOrderDetail.setOtherRemark(costType.getRemark());
            repairOrderDetails.add(repairOrderDetail);
        }

        for (ByKindList.ResultListBean entity : selectByPartsList) {
            if (entity.getId().equals("0")) {
                for (ByPartsEntity byPartsEntity : entity.getCarPartsList()) {
                    RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
                    repairOrderDetail.setType(4);
                    repairOrderDetail.setNum(byPartsEntity.getSelectCount());
                    repairOrderDetail.setPartId(byPartsEntity.getPartsId());
                    repairOrderDetail.setOtherPrice(Double.parseDouble(byPartsEntity.getPrice()));
                    repairOrderDetail.setIsrecommended("1");
                    repairOrderDetail.setMileage(byPartsEntity.getMileage());
                    repairOrderDetail.setPid(byPartsEntity.getPid());
                    repairOrderDetails.add(repairOrderDetail);
                }
            }else {
                for (ByPartsEntity byPartsEntity : entity.getCarPartsList()) {
                    RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
                    repairOrderDetail.setType(4);
                    repairOrderDetail.setNum(byPartsEntity.getSelectCount());
                    repairOrderDetail.setPartId(byPartsEntity.getPartsId());
                    repairOrderDetail.setOtherPrice(Double.parseDouble(byPartsEntity.getPrice()));
                    repairOrderDetail.setIsrecommended("0");
                    repairOrderDetail.setPid(byPartsEntity.getPid());
                    repairOrderDetails.add(repairOrderDetail);
                }

            }
        }

        applyFormEntity.setRepairOrderDetail(repairOrderDetails);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case CHOOSE_PARTS:
                    selectList.clear();
                    List<NewPartsList.ResultListBean.PartsQualityListBean> dataList = data.getParcelableArrayListExtra("data");
                    selectList.addAll(dataList);
                    for (NewPartsList.ResultListBean.PartsQualityListBean parts : selectList) {
                        parts.setEditPrice(parts.getPrice());
                    }
                    fixPartsAdapter.notifyDataSetChanged();
                    break;
                case CHOOSE_PROJECT:
                    selectProjectList.clear();
                    List<Project> projects = data.getParcelableArrayListExtra("data");
                    selectProjectList.addAll(projects);
                    fixProjectAdapter.notifyDataSetChanged();
                    break;
                case OTHER_PAY:
                    CostType costType = data.getParcelableExtra("data");
                    costTypeList.add(costType);
                    costListAdater.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void priceChange(int pos, double price) {
        selectList.get(pos).setEditPrice(price);
    }
}
